//
//  YYController.swift
//  YYProject
//
//  Created by 陆文宇 on 2017/8/16.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import UIKit

class YYController: UIViewController, SVProgressHUDProtocol, NavigationProtocol, YYUmengProtocol, YYAlamofireProtocol, UIScrollViewDelegate {
    
    deinit {
        yy_Log("\(self) deinit")
    }
    
    var routeKey: YYRoute.Key?
    
    var yy_scrollView: UIScrollView!
    var yy_isCustomNaviBar = false
    var yy_needRefreshWhenAppear = false
    var yy_isViewAppear = false
    
    var yy_alphaChangeBoundary = screenWidth * (212 / 375) - 64
    var yy_customNaviBar: UIView!
    var yy_titleLabel: UILabel!
    var yy_leftViews: [UIView]!
    var yy_rightViews: [UIView]!
    
    func yy_configNaviBar(_ naviBar: UINavigationBar!) {
        yy_defaultNaviBarConfig(naviBar)
    }
    
    func yy_configNaviItem(_ naviItem: UINavigationItem) {
        yy_defaultNaviItemConfig(naviItem)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        YYRouter.currentVC = self
        
        if yy_isCustomNaviBar {
            navigationController?.isNavigationBarHidden = true
            navigationController?.view.addSubview(yy_customNaviBar)
        } else {
            navigationController?.isNavigationBarHidden = false
        }
        yy_configNaviBar(navigationController?.navigationBar)
        
        if !yy_isViewAppear {
            if !(self is YYTableController) && !(self is YYCollectionController) && !(self is YYWebController) {
                yy_showStatusHUD()
                yy_requestData()
            }
        }
        
        if yy_needRefreshWhenAppear && yy_isViewAppear {
            if let `self` = self as? YYTableController {
                self.yy_page = 1
            } else if let `self` = self as? YYCollectionController {
                self.yy_page = 1
            }
            yy_requestData()
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        yy_isViewAppear = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        yy_dismissHUD()
        view.endEditing(true)
        
        if yy_isCustomNaviBar {
            yy_customNaviBar.removeFromSuperview()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        yy_config()
        
        yy_configNaviItem(navigationItem)
        if yy_isCustomNaviBar {
            yy_createCustomNavibar()
        }
        
        if #available(iOS 11.0, *) {
            yy_scrollView?.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(yy_keyboardWillShow(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(yy_keyboardWillHide(_:)), name: Notification.Name.UIKeyboardWillHide, object: nil)
    }
    
    func yy_config() {
        yy_defaultConfig()
    }
    
    func yy_createCustomNavibar() {
        var height: CGFloat = 20 + 44
        if #available(iOS 11.0, *) {
            height = navigationController!.view.safeAreaInsets.top + 44
        }
        yy_customNaviBar = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: height))
        yy_customNaviBar.backgroundColor = mainColor.withAlphaComponent(0)
        navigationController?.view.addSubview(yy_customNaviBar)
        
        yy_titleLabel = UILabel()
        yy_titleLabel.textColor = UIColor.white
        yy_titleLabel.text = title
        yy_titleLabel.isHidden = true
        yy_customNaviBar.addSubview(yy_titleLabel)
        yy_titleLabel.snp.makeConstraints { (maker) in
            maker.centerX.equalTo(yy_customNaviBar)
            maker.bottom.equalTo(yy_customNaviBar).offset(-12)
        }
        
        yy_leftViews = [UIView]()
        navigationItem.leftBarButtonItems?.forEach({ (item) in
            let leftView = UIView()
            leftView.alpha = 1
            leftView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
            leftView.layer.cornerRadius = 17
            
            yy_customNaviBar.addSubview(leftView)
            leftView.snp.makeConstraints({ (maker) in
                maker.left.equalTo(yy_leftViews.last ?? yy_customNaviBar).offset(10)
                maker.centerY.equalTo(yy_titleLabel)
                maker.width.equalTo(34)
                maker.height.equalTo(34)
            })
            yy_leftViews.append(leftView)
            
            let leftButton = UIButton()
            leftButton.setImage(item.image, for: UIControlState.normal)
            leftButton.addTarget(item.target, action: item.action!, for: UIControlEvents.touchUpInside)
            yy_customNaviBar.addSubview(leftButton)
            leftButton.snp.makeConstraints { (maker) in
                maker.centerX.equalTo(leftView)
                maker.centerY.equalTo(leftView)
                maker.width.equalTo(30)
                maker.height.equalTo(30)
            }
        })
        
        yy_rightViews = [UIView]()
        navigationItem.rightBarButtonItems?.forEach({ (item) in
            let rightView = UIView()
            rightView.alpha = 1
            rightView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
            rightView.layer.cornerRadius = 17
            
            yy_customNaviBar.addSubview(rightView)
            rightView.snp.makeConstraints({ (maker) in
                maker.right.equalTo(yy_rightViews.last?.snp.left ?? yy_customNaviBar).offset(-10)
                maker.centerY.equalTo(yy_titleLabel)
                maker.width.equalTo(34)
                maker.height.equalTo(34)
            })
            yy_rightViews.append(rightView)
            
            let rightButton = UIButton()
            rightButton.setImage(item.image, for: UIControlState.normal)
            rightButton.addTarget(item.target, action: item.action!, for: UIControlEvents.touchUpInside)
            yy_customNaviBar.addSubview(rightButton)
            rightButton.snp.makeConstraints { (make) in
                make.centerX.equalTo(rightView)
                make.centerY.equalTo(rightView)
                make.width.equalTo(30)
                make.height.equalTo(30)
            }
        })
    }
    
    func yy_requestData() {
        yy_dismissHUD()
    }
    
    func yy_analyzData(_ data: Any) -> [YYModel]? {
        yy_dismissHUD()
        return nil
    }
    
    func yy_handlerData(_ data: [YYModel]?) {
        guard data != nil else {
            return
        }
    }
    
    func yy_requestFailure(errmsg: String) -> String? {
        yy_dismissHUD()
        return errmsg
    }
    
    func yy_shouldPop() -> Bool {
        return true
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    @objc func yy_keyboardWillShow(_ notification: Notification) {
        
    }
    
    @objc func yy_keyboardWillHide(_ notification: Notification) {
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard yy_isCustomNaviBar && yy_scrollView === scrollView else {
            return
        }
        
        let offsetY = scrollView.contentOffset.y
        if offsetY >= 0 && offsetY <= yy_alphaChangeBoundary {
            yy_customNaviBar.backgroundColor = mainColor.withAlphaComponent(offsetY / yy_alphaChangeBoundary)
            yy_titleLabel.isHidden = true
            yy_leftViews.forEach({ (leftView) in
                leftView.alpha = 1 - offsetY / yy_alphaChangeBoundary
            })
            yy_rightViews.forEach({ (rightView) in
                rightView.alpha = 1 - offsetY / yy_alphaChangeBoundary
            })
        } else if offsetY > yy_alphaChangeBoundary {
            yy_titleLabel.isHidden = false
            yy_customNaviBar.backgroundColor = mainColor
            yy_leftViews.forEach({ (leftView) in
                leftView.alpha = 0
            })
            yy_rightViews.forEach({ (rightView) in
                rightView.alpha = 0
            })
        } else {
            yy_customNaviBar.backgroundColor = mainColor.withAlphaComponent(0)
            yy_titleLabel.isHidden = true
            yy_leftViews.forEach({ (leftView) in
                leftView.alpha = 1
            })
            yy_rightViews.forEach({ (rightView) in
                rightView.alpha = 1
            })
        }
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        
        view.endEditing(true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

